package com.ciwong.epaper.modules.cordva;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.common.CheckIsExamForDetail;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.modules.me.util.UploadFileHelper;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.gson.Gson;

/**
 * Created by neo on 2016/8/24.
 */
public class VideoExplainOnlineAnswerResultActivity extends BaseActivity {
    private Context mContext = this;
    public static final String TAG = "ciwong";
    private TextView tv_show_total_time, tvScore;
    private Button btnSubmit;
    //提交答案所需要信息
    private DownLoadInfo mDownLoadInfo;
    private Module mModule;
    private int totalTime = 0;
    private UserInfoBase userInfo;
    private String workId = "0";
    private int type;
    private int position;
    private String mDoWorkId;
    private String mJsonSource;
    private Gson mGson = new Gson();
    private CWDialog mDialog;
    private String score = "0.0";

    private int mJumpSourcePage;

    private int mServiceId;
    private String classId;
    private Answer submitFailedAnswer;
    /**
     * 正在提交中
     */
    ImageView iv_circle;
    /**
     *
     */
    LinearLayout ll_submiting;

    @Override
    protected int setView() {
        return R.layout.activity_video_explain_online_answer_result;
    }


    @Override
    protected void findViews() {
        ll_submiting = (LinearLayout) findViewById(R.id.ll_submiting);
        iv_circle = (ImageView) findViewById(R.id.iv_circle);
        tv_show_total_time = (TextView) findViewById(R.id.tv_show_total_time);
        btnSubmit = (Button) findViewById(R.id.submit_btn);
        tvScore = (TextView) findViewById(R.id.ls_result_score);

    }

    @Override
    protected void initEvent() {

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!NetworkUtils.isOnline()) {
                    showToastError("网络不可用，请连接网络后重试");
                    btnSubmit.setEnabled(true);
                    return;
                }
                btnSubmit.setEnabled(false);

                if (btnSubmit.getText().toString().equals("重新提交")) {
                    submitAgain();
                } else {
                    submit();
                }

            }
        });
        EventBus.getDefault().register(this);

    }


    public void onEventMainThread(Answer answer) {
        updateSubmitStatus(answer);//更新作业提交的状态
    }

    private void updateSubmitStatus(Answer answer) {
        System.out.println("answer.getSubmitStatus()" + answer.getSubmitStatus());
        switch (answer.getSubmitStatus()) {
            case 15:
                showToastError("classid非Integer");
                btnSubmit.setEnabled(true);
                hideSubmitingCircle();
                btnSubmit.setText("重新提交");
            case 17:
                showToastError("登录失效");
                hideSubmitingCircle();
                btnSubmit.setText("重新提交");
                finish();
                break;
            case Answer.SubmitStatus.SUBMIT_WORK_CARD_NOT_EXIST:
                break;
            case Answer.SubmitStatus.SUBMIT_WORK_NO_CLASS_ERROR:
                break;
            case Answer.SubmitStatus.WORK_FILE_SUBMIT_FAILE:
                btnSubmit.setEnabled(true);
                hideSubmitingCircle();
                showToastError("作业提交失败");
                btnSubmit.setText("重新提交");
                break;
            case Answer.SubmitStatus.WORK_NO_ADD_CLASS_SUBMIT_FAILE:
                btnSubmit.setEnabled(true);
                break;
            case Answer.SubmitStatus.WORK_NO_SCORE_FAILE:
                break;
            case Answer.SubmitStatus.WORK_SUBMIT_FAILE:
                btnSubmit.setEnabled(true);
                hideSubmitingCircle();
                showToastError("作业提交失败");
                btnSubmit.setText("重新提交");
                break;
            case Answer.SubmitStatus.WORK_SUBMIT_SUCCUED:
                hideSubmitingCircle();
                showSubmitSuccuedDialog(answer);
                //把本地保存的作业删除
                if (!TextUtils.isEmpty(answer.getVersionId()) && answer.getVersionId().equals(mModule.getResourceList().get(position).getVersionId())) {
                    SerializableManager.getInstance().serialize("FailedAnswer" + position + mModule.getResourceList().get(position).getVersionId() + workId, null);
                }
                setResult(RESULT_OK);
                break;
            case Answer.SubmitStatus.WORK_SUBMITING:
                submitFailedAnswer = answer;
                showSubmitingCircle();
                break;
            default:
                break;
        }
    }

    private RotateAnimation rotaAnimation;

    private void showSubmitingCircle() {
        ll_submiting.setVisibility(View.VISIBLE);
//        Drawable circleBackDrawable = CWProgressBar.getDrawableFromJar("/images_progressbar/loading.png", CWProgressBar.class);
        iv_circle.setBackgroundResource(R.mipmap.loading);
        ll_submiting.setVisibility(View.VISIBLE);
        if (rotaAnimation == null) {
            rotaAnimation = new RotateAnimation(0.0F, 357.0F, 1, 0.5F, 1, 0.5F);
        }
        iv_circle.setAnimation(rotaAnimation);
        rotaAnimation.setRepeatCount(ValueAnimator.INFINITE);
        rotaAnimation.setDuration(2000L);
        rotaAnimation.setFillAfter(false);
        rotaAnimation.setInterpolator(new LinearInterpolator());
        rotaAnimation.startNow();
    }

    private void hideSubmitingCircle() {
        ll_submiting.setVisibility(View.GONE);
        if (rotaAnimation != null) {
            iv_circle.clearAnimation();
        }
    }


    private void submit() {
        if (tempAnswer == null) {
            tempAnswer = submitFailedAnswer;
        }
        showSubmitingCircle();
        UploadFileHelper.getInstance().submitAnswer(tempAnswer,
                getUserInfoBase().getUserId(), new SubmitBaseCallBack(true), mHandler, tempAnswer.getModuleId());
    }

    private void submitAgain() { //重新提交
        UploadFileHelper.getInstance().submitAnswer(submitFailedAnswer,
                getUserInfoBase().getUserId(), new SubmitBaseCallBack(true), mHandler, submitFailedAnswer.getModuleId());
    }

    private Handler mHandler = new Handler(Looper.getMainLooper());

    /**
     * 未加入班级提示框
     */
    private void showConfirmAddClassDialog() {
        final CWDialog dialog = new CWDialog(this, false, false);
        dialog.setMessage(R.string.no_add_class_tip);
        dialog.setCancelable(true);
        dialog.setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
                btnSubmit.setEnabled(true);
            }
        });
        dialog.setPositiveButton(getString(R.string.add_class),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MeJumpManager.jumpToJoinClassActivity(R.string.go_back,
                                VideoExplainOnlineAnswerResultActivity.this,
                                IntentValue.JumpToJoinClassType.FROM_CLASS_LIST,
                                EpaperConstant.REQUEST_CODE_VIDEO_EXPLAIN_ONLINE_JOIN_CLASS);
                    }
                }, true)
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EpaperConstant.REQUEST_CODE_VIDEO_EXPLAIN_ONLINE_JOIN_CLASS:
//                    submit(mJsonSource);
                    submit();
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            btnSubmit.setEnabled(true);
        }
    }

    @Override
    protected void init() {
        setTitleText("成绩");
        mDialog = new CWDialog(this);
    }

    private boolean resubmit = false;

    @Override
    protected void loadData() {
        Intent intent = getIntent();
        type = intent.getIntExtra(IntentFlag.INTENT_FLAG_TYPE, -1);
        mDoWorkId = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_DO_WORK_ID);

        if (null != mDoWorkId && mDoWorkId.equals("0")) {
            mDoWorkId = null;
        }
        //在此保存提交答案所需信息
        if (null != intent) {
            resubmit = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_RESUBMIT, false);
            mDownLoadInfo = (DownLoadInfo) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
            mModule = (Module) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
            workId = intent.getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
            if (TextUtils.isEmpty(workId)) {
                workId = "0";
            }
            position = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
            mJsonSource = intent.getStringExtra(IntentFlag.INTENT_FLAG_STR);
            totalTime = intent.getIntExtra(IntentFlag.INTENT_FLAG_WORK_TIME, 0);
            score = intent.getStringExtra(IntentFlag.INTENT_FLAG_WORK_SCORE);
            mJumpSourcePage = intent.getIntExtra(IntentFlag.INTENT_FLAG_H5_PAGE_TYPE_SOURCE, -1);
            mServiceId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);
            classId = intent.getStringExtra(IntentFlag.INTENT_FLAG_CLASS_ID);
            submitFailedAnswer = (Answer) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_ANSWER);
            if (submitFailedAnswer != null && totalTime <= 0) {
                totalTime = submitFailedAnswer.getWorkLong();
            }
            tv_show_total_time.setText(ListenSpeakUtil.formatWorkLong(this, totalTime));

            float totalScore = 0f;// 总分

            String scoreText = "0.0";
            if (submitFailedAnswer != null) {
                if ((Float.valueOf(submitFailedAnswer.getActualScore()) <= 0.0f)) {
                    totalScore = 0f + submitFailedAnswer.getActualScore();
                    scoreText = getString(R.string.speech_word_score, MeUtil.formatScore(totalScore));
                } else {
                    scoreText = getString(R.string.speech_word_score, submitFailedAnswer.getActualScore() + "");
                }

            }
            if (scoreText.indexOf(".") > 0) {
                //正则表达
                scoreText = scoreText.replaceAll("0+?$", "");//去掉后面无用的零
                scoreText = scoreText.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点
            }
            if (resubmit) {
                btnSubmit.setText("重新提交");
            } else {
                btnSubmit.setText("交作业");
            }
            SpannableString ss = new SpannableString(scoreText + "分");
            ss.setSpan(new RelativeSizeSpan(2), 0, ss.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvScore.setText(ss);
        }

    }

    /**
     * 根据前面的作答，生成的临时answer
     */
    Answer tempAnswer = null;


    class SubmitBaseCallBack extends BaseCallBack {

        private boolean isShowSubmitingDialog;

        public SubmitBaseCallBack(boolean isShowSubmitingDialog) {
            this.isShowSubmitingDialog = isShowSubmitingDialog;
        }

        @Override
        public void success(Object data) {
        }

        @Override
        public void success() {
            setResult(RESULT_OK);
        }

        @Override
        public void failed(Object data) {
        }

        @Override
        public void failed(int errorCode, Object data) {
        }

    }

    private void showSubmitSuccuedDialog(final Answer answer) {
        mDialog.setMessage("作业提交成功!");
        mDialog.setCancelable(false);
        mDialog.setPositiveButton(R.string.look_detail,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setResult(RESULT_OK);
                        mDialog.dismiss();
                        finish();

                        if (mJumpSourcePage != EpaperConstant.H5_PAGE_TYPE_STUDY_RECORD) {
                            boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(VideoExplainOnlineAnswerResultActivity.this, answer.getContentId() + "", 0);
                            if (!orNotWatchDetails)
                                return;
                            MeJumpManager.jumpToStudyRecordH5Activity(-1, VideoExplainOnlineAnswerResultActivity.this, R.string.go_back,
                                    RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_WORK_LIST, "", "", 0);

                        }

                    }
                }).setNegativeButton(R.string.str_return_homework_list,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        setResult(RESULT_OK);
                        mDialog.dismiss();
                        finish();
                    }
                })
                .show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void finish() {
        if (submitFailedAnswer != null && submitFailedAnswer.getSubmitStatus() == Answer.SubmitStatus.WORK_SUBMITING) {//作业正在提交中
            showAreYouSureQuitDialog();

        }
        hideSubmitingCircle();
        super.finish();
    }

    private void showAreYouSureQuitDialog() {
        mDialog.setMessage(R.string.submit_work_submiting);
        mDialog.setCancelable(false);
        mDialog.setTitle("提示");
        mDialog.setPositiveButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setResult(RESULT_OK);
                        mDialog.dismiss();

                    }
                }).setNegativeButton(R.string.str_confirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        setResult(RESULT_OK);
                        mDialog.dismiss();
                        finish();
                    }
                })
                .show();
    }

}
